﻿using System;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.Mvc;

namespace Wild2
{
    public partial class Default : Page
    {
        private void Transfer(string url)
        {
            // Create URI builder
            var uriBuilder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port, Request.ApplicationPath);
            // Add destination URI
            uriBuilder.Path += url;
            // Because UriBuilder escapes URI decode before passing as an argument
            string path = Server.UrlDecode(uriBuilder.Uri.PathAndQuery);
            // Rewrite path
            HttpContext.Current.RewritePath(path, false);
            IHttpHandler httpHandler = new MvcHttpHandler();
            // Process request
            httpHandler.ProcessRequest(HttpContext.Current);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            Response.Cache.SetLastModified(DateTime.Now.AddYears(-1));
            Response.Charset = "utf-8";
            if (Request.Browser.IsMobileDevice) { Response.ContentType = "application/xhtml+xml"; }

            try
            {
                if (Request.QueryString["dev"] != null)
                {
                    Session[Wild2.Models.Constants.SessionConstants.DEV] = Convert.ToInt32(Request.QueryString["dev"]);
                }
            }
            catch (Exception ex) { Models.Logger.Log(ex, null); }

            try
            {
                if (Request.QueryString["adv"] != null)
                {
                    using (SqlConnection connStat = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectStatistic"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO advert([IP], [XIP], [UserAgent], [Referrer], [date], [SessionString], [Params])
                                                 VALUES(@IP, @XIP, @UserAgent, @Referrer, GETDATE(), @S, @P)", connStat);
                        cmd.Parameters.Add("@IP", SqlDbType.NVarChar, 20).Value = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) cmd.Parameters.Add("@XIP", SqlDbType.NVarChar, 20).Value = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                        else cmd.Parameters.Add("@XIP", SqlDbType.NVarChar, 20).Value = DBNull.Value;
                        cmd.Parameters.Add("@UserAgent", SqlDbType.NVarChar, 100).Value = Request.UserAgent;
                        cmd.Parameters.Add("@Referrer", SqlDbType.NVarChar, 200).Value = Request.UrlReferrer != null
                                                                                      ? (object)
                                                                                        Request.UrlReferrer.OriginalString
                                                                                      : DBNull.Value;
                        cmd.Parameters.Add("@S", SqlDbType.NVarChar, 100).Value = Session.SessionID;
                        cmd.Parameters.Add("@P", SqlDbType.NVarChar, 50).Value = Request.QueryString["adv"];
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();
                        cmd.Connection.Close();
                    }
                }
            } 
            catch (Exception ex) { Models.Logger.Log(ex, null); }


            try
            {
                if (Request.UrlReferrer != null)
                {
                    if (Request.UrlReferrer.OriginalString != "")
                    {
                        if (Request.UrlReferrer.OriginalString.ToLower().IndexOf(ConfigurationManager.AppSettings["domainshort"], StringComparison.Ordinal) == -1)
                        {
                            using (SqlConnection connStat = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectStatistic"].ConnectionString))
                            {
                                SqlCommand cmd = new SqlCommand("INSERT INTO Referrers([IP], [XIP], [UserAgent], [Page], [Date], [Referrer]) VALUES(@IP, @XIP, @UserAgent, @Page, GETDATE(), @Referrer)", connStat);
                                cmd.Parameters.Add("@IP", SqlDbType.NVarChar, 20).Value = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                                if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) cmd.Parameters.Add("@XIP", SqlDbType.NVarChar, 20).Value = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                                else cmd.Parameters.Add("@XIP", SqlDbType.NVarChar, 20).Value = DBNull.Value;
                                cmd.Parameters.Add("@UserAgent", SqlDbType.NVarChar, 100).Value = Request.UserAgent;
                                //cmd.Parameters.Add("@Page", System.Data.SqlDbType.NVarChar, 200).Value = Request.RawUrl;
                                cmd.Parameters.Add("@Page", SqlDbType.NVarChar, 200).Value = Request.Url.ToString();
                                cmd.Parameters.Add("@Referrer", SqlDbType.NVarChar, 4000).Value = Request.UrlReferrer.OriginalString;
                                
                                cmd.Connection.Open();
                                cmd.ExecuteNonQuery();
                                cmd.Connection.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex) { Models.Logger.Log(ex, null); }

            //Response.Redirect(Response.ApplyAppPathModifier("~/0.aspx"));
            Transfer("/Home.aspx/Index");
        }
    }
}